<?php
// +----------------------------------------------------------------------
// | Exchanges
// +----------------------------------------------------------------------
// | Author: derek <693472824@qq.com> <http://www.bloveambition.com/>
// +----------------------------------------------------------------------

namespace Api\Controller;
use Think\Model;
use Api\Logic\UserLogic;

/**
 * 后台登录控制器
 * @author derek <693472824@qq.com>
 */
class PublicController extends BaseController {

    /**
     * 用户登录
     * @author derek <693472824@qq.com>
     */
    public function login(){
        
        if(IS_AJAX){
        
            $data['tel'] = I('tel');
            $data['pwd'] = I('pwd');
            $data['remember'] = I('remember');
            
            $times = S($data['tel'].'login_times') ? : 0;
            
            /* 密码输错3次以上需检测验证码: */
            if($times > 2){
                
                $verify = I('verify');
                if(empty($verify)){
                    
                    $this->result['status'] = '-201';
                    $this->result['times'] = $times;
                    $this->ajaxReturn($this->result);
                }else{
                
                    $verifyModel = new \Think\Verify();
                    if(!$verifyModel->check($verify, C('VERIFY_CODE_ID'))){
                        $this->result['status'] = '-202';
                        $this->ajaxReturn($this->result);
                    }
                }
            }
            
            if($data['remember'] == '1'){
                //记住账号30天
                cookie('login_tel', $data['tel'], 2592000);
            }
            
            /* 调用业务层登录接口 */
            $userLogic = D('User', 'Logic');
            $uid = $userLogic->login($data['tel'], $data['pwd']);
        
            if(0 < $uid){ //登录成功
                
                S($data['tel'].'login_times', null);
                $this->result['status'] = '1';
            } else { //登录失败
                
                $times = $times + 1;
                
                S($data['tel'].'login_times', $times + 1, 1800);
                
                if($times > 2){
                    $this->result['times'] = $times;
                }
                
                $this->result['status'] = '-1';
            }
            
            $this->ajaxReturn($this->result);
        } else {
            if(UserLogic::is_login()){
                $this->redirect('Index/index');
            }else{
                
                //来源链接地址
                $historyURL = I('historyURL');
                $historyURL = $historyURL ? urldecode($historyURL) : '';
                
                $tel = cookie('login_tel');
                $times = S($tel.'login_times') ? : 0;
                
                if($times > 2){
                    $this->assign('display', '1');
                }
                
                $this->assign('tel', $tel);
                $this->assign('historyURL', $historyURL);
                $this->display();
            }
        }
    }
    
    /**
     * 发送验证码
     * @param integer account   手机号
     * @param integer type      操作类型 1：新注册；2：找回密码
     * @author derek <693472824@qq.com>
     */
    public function validate(){
    
        $account = I('tel');
        $type = I('type');
        
        if($type == '3'){
            $account = UserLogic::getAccount();
        }
    
        if(!is_numeric($account) || !checkMobile($account) || !is_numeric($type)){
            $this->result['status'] = '422';
            $this->rsp['rspDesc'] = '参数异常';
            $this->ajaxReturn($this->result);
        }
    
        //是否被禁止发送验证码
        $forbidden = false;
    
        $userModel = M('User')->where(array('account'=>$account))->find();
    
        if($type == '1' && !empty($userModel)){
    
            $forbidden = true;
            $this->result['status'] = '108';
            $this->result['msg'] = '账号已被注册';
        }elseif($type == '2' && empty($userModel)){
    
            $forbidden = true;
            $this->result['status'] = '109';
            $this->result['msg'] = '账号不存在';
        }
    
        if(!$forbidden){
    
            $config = S('DB_CONFIG_DATA');
            $effectiveTime = $config['EFFECTIVE_TIME'] ? $config['EFFECTIVE_TIME'] : 30;
    
            $validateInfo = S('validate.'.$account);
    
            if($validateInfo){
    
                $maxFrequency = $config['MAX_VALIDATE_CODE_FREQUENCY'] ? $config['MAX_VALIDATE_CODE_FREQUENCY'] : 10;
    
                $count = $validateInfo['count'] + 1;
    
                //有效时间（EFFECTIVE_TIME）内，发送验证码超越规定次数（MAX_VALIDATE_CODE_FREQUENCY）时，限制账号EFFECTIVE_TIME分钟
                if(NOW_TIME - $validateInfo['starttime'] < $effectiveTime * 60 && $count > $maxFrequency){
                    $forbidden = true;
                    $this->result['status'] = '102';
                    $this->result['msg'] = '发送验证码太频繁';
                }
            }
    
            if(!$forbidden){
    
                //生成验证码
                $validation = rand(100000, 999999);
                $message = C('VALIDATE_MESSAGE') ? C('VALIDATE_MESSAGE') : '您此次的验证码为：#code#，#effective#分钟内有效！';
    
                $message = str_replace('#code#', $validation, $message);
                $message = str_replace('#effective#', $effectiveTime, $message);
    
                $result =  api('Util/sendCode', array($account, $message));
                
                if($result == '1'){
    
                    $validateInfo['starttime'] = $validateInfo['starttime'] ? $validateInfo['starttime'] : NOW_TIME;
                    $validateInfo['count'] = $validateInfo['count'] ? $validateInfo['count'] + 1 : 1;
                    $validateInfo['validation'] = $validation;
                    S('validate.'.$account, $validateInfo, $effectiveTime * 60);
    
                    $this->result['status'] = '200';
                    //$this->result['msg'] = '发送成功';
                }else{
    
                    $this->result['status'] = '303';
                    //$this->result['msg'] = '发送失败，请重新发送';
                }
            }
        }
    
        $this->ajaxReturn($this->result);
    }
    
    
    /**
     * 用户注册/重置密码
     * @param string account       手机号
     * @param string validation    验证码
     * @param string password      密码
     * @param string type          操作类型 1：新注册；2：找回密码
     * @author derek <693472824@qq.com>
     */
    public function register() {
        
        $type = I('type');
        $type = $type ? : '1';
        $referee = I('referee');
        
        if(IS_AJAX){
            
            $account = I('tel');
            $validation = I('validation');
            $password = I('pwd');
            
            if(!checkMobile($account) || !is_numeric($validation) || !is_numeric($type)){
                $this->result['status'] = '422';
                //$this->result['msg'] = '参数异常';
                $this->ajaxReturn($this->result);
            }
            
            //账号-验证码信息
            $validateInfo = S('validate.'.$account);
            
            if(!is_array($validateInfo) || $validation <> $validateInfo['validation']){
                $this->result['status'] = '103';
                //$this->result['msg'] = '验证码错误';
                $this->ajaxReturn($this->result);
            }
    
            $userModel = M('User')->where(array('account'=>$account))->find();
            
            //type  1：新注册；2：重置密码
            if($type == '1' && !empty($userModel)){
            
                $this->result['status'] = '108';
                //$this->result['msg'] = '账号已被注册';
                
                $this->ajaxReturn($this->result);
            }elseif($type <> '1' && empty($userModel)){
            
                $this->result['status'] = '109';
                //$this->result['msg'] = '账号不存在';
                
                $this->ajaxReturn($this->result);
            }
            
            $data = array('account'=>$account, 'password'=>$password, 
                        'last_login_time'=>NOW_TIME, 'last_login_ip'=>get_client_ip(1));
            
            $user = D('User');
            $opType = $type == '1' ? Model::MODEL_INSERT : Model::MODEL_UPDATE;
            
            //新增或更新用户数据
            if($user->create($data, $opType)){
                if($type == '1'){
                    
                    $result = $user->add();
                    
                    //注册用户获得优惠券
                    $value = C('REGISTER_COUPON_VALUE');
                    $userLogic = D('User', 'Logic');
                    $userLogic->coupon('1', $value, $random='', $result);
                    
                    //邀请好友注册成功后，邀请者获得优惠券
                    if(!empty($referee)){
                        $refereeModel = $user->find($referee);
                        if(!empty($refereeModel)){
                            $value = C('INVITE_COUPON_VALUE');
                            $userLogic->coupon('2', $value, $random='', $referee);
                        }
                    }
                    
                }else if($type == '2'){
                    
                    $result = $user->where(array('account'=>$account))->save();
                }
            }
                
            //数据库更新成功
            if($result){
                
                $this->result['status'] = '200';
            }else{
                $this->result['status'] = '301';
                $this->result['msg'] = '操作失败';
            }
            
            $this->ajaxReturn($this->result);
        }else{
            
            $this->assign('type', $type);
            $this->assign('referee', $referee);
            $this->display();
        }
    }
    
    
    /**
     * 注销登录
     * @author derek <693472824@qq.com>
     */
    public function logout(){
        
        $userID = UserLogic::is_login();
        
        if(!empty($userID)){
            
            $userLogic = D('User', 'Logic');
            $userLogic->logout();
            
        }
        
        $this->redirect('Public/login');
    }
    
    /**
     * 生成验证码
     * @author derek <693472824@qq.com>
     */
    public function verify(){
        
        $config =    array(
                'codeSet'     =>    '0123456789',
                'length'      =>    4,     // 验证码位数
        );
        
        $verify = new \Think\Verify($config);
        $verify->entry(C('VERIFY_CODE_ID'));
    }
    
    /**
     * ajax 校验验证码
     * @author derek <693472824@qq.com>
     */
    public function ajaxVerify(){
        
        $verify = I('param');
        
        $result = $this->checkVerify($verify);

        if($result === true){
            
            echo 'y';
        }else{
            
            echo '验证码错误';
        }
    }
    
    /**
     * 校验验证码
     * @author derek <693472824@qq.com>
     */
    protected function checkVerify($verify){
        
        $verifyModel = new \Think\Verify();
        
        if($verifyModel->check($verify, C('VERIFY_CODE_ID'))){
            
            return true;
        }else{
            
            return false;
        }
    }
    
    /**
     * 用户协议
     * @author derek <693472824@qq.com>
     */
    public function agreement(){
            
        $content = C('USER_AGREEMENT');
        
        $this->assign('content', $content);
        $this->display();
    }
    
    /**
     * 关于小哥
     */
    public function about(){
        
        $about = C('ABOUT_US');
        
        $this->assign('content', $about);
        $this->display();
    }
    
    /**
     * 老年人便捷通道
     */
    public function convenient(){
        
        $about = C('CONVENIENT_CONTENT');
        
        $this->assign('convenient', $about);
        $this->display();
    }
}
